<?php
/**
 * 创客空间
 * @author Administrator
 *
 */
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use \Cache;
use \DB;

class Maker extends Model
{
    protected $table = 'maker';

    protected function getDateFormat()
    {
        return 'U';
    }
    
    static function getLists($where){
    	$result = self::whereRaw(implode(" and ",$where))->get();
    	return $result;
    }

    public function city(){
    	return $this->belongsTo('App\Models\Zone','city_id','id'); 
    }

    public function makerUser()
    {
        return $this->hasMany('App\Models\UserInfo', 'uid', 'uid');
    }

    /*
     * 获取全部创客空间对象
     */
    static function selectAllMakers(){
    	if(!Cache::has('all_maker')){
    		$makers=Maker::whereRaw("status=1")->get();
    		Cache::forever('all_maker', $makers,1);
    	}
    	return Cache::get('all_maker');
    }
    /*
     * 获取推荐的创客空间对象
    */
    static function recommendMakers(){
    	if(!Cache::has('recommend_maker')){
    		$makers=Maker::whereRaw("status=1 and recommend")->get();
    		Cache::forever('recommend_maker', $makers,1000);
    	}
    	return Cache::get('recommend_maker');
    }
    /*
     * 获取创客空间创始人信息
     */
    static function getLeaderUserinfo($id){
    	$makerUserInfo= DB::table('maker_user')
    	->leftJoin('user','user.uid','=','maker_user.uid')
    	->leftJoin('userinfo','userinfo.uid','=','user.uid')
    	->select('user.uid','user.realname','userinfo.mobile')
    	->whereRaw('lab_maker_user.maker_id= '.$id.' and lab_maker_user.is_leader=1')
    	->first();
    	return $makerUserInfo;
    }
    /*
     * 获取创客空间数据公用合集
     */
    static function getMakerDatas($v){
    	$data=array();
    	$leaderUserinfo=self::getLeaderUserinfo($v->id);
    	$data['uid']=$leaderUserinfo['uid'];
    	$data['realname']=$leaderUserinfo['realname'];
    	$data['mobile']=$leaderUserinfo['mobile'];
    	$data['id']=$v->id;
		$data['name']=$v->name;
		$data['remark']=$v->remark;
		$data['image']=$v->image;
		return $data;
    }

    /**
     * 根据活动id活动主办方空间信息
     */
    static function getMakerByActid($actid){
    	$res = DB::table('maker_activity')
    	->leftJoin('maker','maker.id','=','maker_activity.maker_id')
    	->select('maker.*')
    	->whereRaw('lab_maker_activity.activity_id= '.$actid.' and lab_maker_activity.type="organizer"')
    	->first();
    	return $res;
    }

    /**
     * 根据Maker_id获取创客空间的城市、名字和头像
     */
    static function getMakerInformation($maker_ids){
        $makers = self::with('City')->whereIn('id',$maker_ids)->get();
        foreach ($makers as $key => $val) {
            $makers_info[$key]['id'] = $val->id;
            $makers_info[$key]['city'] = $val->City->name;
            $makers_info[$key]['name'] = $val->name;
            $makers_info[$key]['image'] = $val->image;
        }
        return $makers_info;
    }
}
